import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { fetchCommentRowsAPI, fetchServiceAPI, findGoodDetailAPI } from "@/api/goodDetailAPI";
import type { GoodDetail, ListRowsParams, ServiceItem } from "@/type/GoodDetailType";
import type { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";
import type { AsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import type { Comment } from "@/type/GoodDetailType";

type InitialState = {
   goodDetail: GoodDetail,
   comment: Comment[],
   serviceList: ServiceItem[]
}

const initialState: InitialState = {
   goodDetail: {} as GoodDetail,
   comment: [],
   serviceList: [],
};

/**
 * @description 获取商品详情的AsyncThunk函数
 * */
export const findGoodDetailThunk: AsyncThunk<GoodDetail, string, AsyncThunkConfig> = createAsyncThunk("findGoodDetailThunk", async (goodsId, { rejectWithValue }) => {
   try {
      const { data: { detail } } = await findGoodDetailAPI(goodsId);
      return detail;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 获取详情页面商品评价的AsyncThunk
 * */
export const fetchCommentRowsThunk: AsyncThunk<Comment[], ListRowsParams, AsyncThunkConfig> = createAsyncThunk("fetchCommentRowsThunk", async (params, { rejectWithValue }) => {
   try {
      const { data: { list } } = await fetchCommentRowsAPI(params);
      return list;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

export const fetchServiceThunk: AsyncThunk<ServiceItem[], number | string, AsyncThunkConfig> = createAsyncThunk("fetchServiceThunk", async (goodsId, { rejectWithValue }) => {
   try {
      const { data: { list } } = await fetchServiceAPI(goodsId);
      return list;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const goodDetailStore = createSlice({
   name: "goodDetailStore",
   initialState,
   reducers: {},
   extraReducers(builder) {
      builder.addCase(findGoodDetailThunk.fulfilled, (state: InitialState, action: PayloadAction<GoodDetail>) => {
         state.goodDetail = action.payload;
      });
      builder.addCase(fetchCommentRowsThunk.fulfilled, (state: InitialState, action: PayloadAction<Comment[]>) => {
         state.comment = action.payload;
      });
      builder.addCase(fetchServiceThunk.fulfilled, (state: InitialState, action: PayloadAction<ServiceItem[]>) => {
         state.serviceList = action.payload;
      });
   },
});

export default goodDetailStore.reducer;
